package com.angis.fx.activity.jcdj;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.angis.fx.activity.R;
import com.angis.fx.activity.login.LoginActivity;
import com.angis.fx.db.QuickTextDBHelper;

public class QuickTextActivity extends Activity implements OnItemClickListener {

	private ListView mListView;
	private EditText mQt_add_et;
	private QuickTextDBHelper mQtDBHelper;
	private MyAdapter mSimpleAdapter;
	private List<Map<String, String>> mQktextList;
	private String[] from = { "name" };
	private int[] to = { R.id.qklist_name };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quicktextactivity);
		mListView = (ListView) findViewById(R.id.qk_listview);
		mQktextList = new ArrayList<Map<String, String>>();
		queryQT();
		mSimpleAdapter = new MyAdapter(this, mQktextList, R.layout.quicktextlist, from, to);
		mListView.setAdapter(mSimpleAdapter);
		mListView.setOnItemClickListener(this);
	}

	private void queryQT() {
		mQktextList.clear();
		mQtDBHelper = new QuickTextDBHelper(QuickTextActivity.this);
		Cursor lCursor = mQtDBHelper.getAllQuickText();
		if (lCursor.moveToFirst()) {
			do {
				String qid = lCursor.getString(0);
				String detail = lCursor.getString(1);
				// String qcreationtime = lCursor.getString(2);
				// String creationuser = lCursor.getString(3);
				Map<String, String> lMap = new HashMap<String, String>();
				lMap.put("name", detail + "::" + qid);
				mQktextList.add(lMap);
			} while (lCursor.moveToNext());
		}
		lCursor.close();
		mQtDBHelper.closeDB();
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position,
			long arg3) {
		CheckBox checkBox = (CheckBox) view.findViewById(R.id.qklist_ck);
		checkBox.toggle();
		mSimpleAdapter.map.put(position, checkBox.isChecked());
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "新建");
		menu.add(0, 1, 0, "编辑");
		menu.add(0, 2, 0, "删除");
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		LayoutInflater lInflater = LayoutInflater.from(this);
		final View lView = lInflater.inflate(R.layout.quicktextadd, null);
		Map<Integer, Boolean> lMap = mSimpleAdapter.map;
		Integer lCountChecked = 0;
		final List<Integer> lPos = new ArrayList<Integer>();
		for (Entry<Integer, Boolean> entry : lMap.entrySet()) {
			Boolean isChecked = entry.getValue();
			if (isChecked) {
				lPos.add(entry.getKey());
				lCountChecked++;
			}
		}
		switch (item.getItemId()) {
		case 0:
			new AlertDialog.Builder(this).setTitle("新增")
					.setView(lView).setPositiveButton("保存",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									mQt_add_et = (EditText) lView.findViewById(R.id.qt_add_et);
									String lDetail = mQt_add_et.getText().toString();
									if (null != lDetail && lDetail.length() > 0) {
										SimpleDateFormat lSdf = new SimpleDateFormat("yyyy-MM-dd");
										Calendar lCal = Calendar.getInstance();
										String lDate = lSdf.format(lCal.getTime());
										String lUUID = UUID.randomUUID().toString();
										mQtDBHelper = new QuickTextDBHelper(QuickTextActivity.this);
										mQtDBHelper.insertQuickText(lUUID, lDetail, lDate, LoginActivity.g_username);
										mQtDBHelper.closeDB();
										Map<String, String> lMap = new HashMap<String, String>();
										lMap.put("name", lDetail + "::" + lUUID);
										mQktextList.add(lMap);
										mSimpleAdapter = new MyAdapter(QuickTextActivity.this, mQktextList, R.layout.quicktextlist, from, to);
										mListView.setAdapter(mSimpleAdapter);
										mListView.invalidateViews();
									}
								}
							}).setNegativeButton("返回",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									dialog.cancel();
								}
							}).create().show();
			break;
		case 1:
			if (lCountChecked == 1) {
				String[] lStr = mSimpleAdapter.getView(lPos.get(0), lView);
				mQt_add_et = (EditText) lView.findViewById(R.id.qt_add_et);
				mQt_add_et.setText(lStr[0]);
				final String lId = lStr[1];
				new AlertDialog.Builder(this).setTitle("编辑")
						.setView(lView).setPositiveButton("更新",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int whichButton) {
										mQt_add_et = (EditText) lView.findViewById(R.id.qt_add_et);
										String lDetail = mQt_add_et.getText().toString();
										if (null != lDetail && lDetail.length() > 0) {
											SimpleDateFormat lSdf = new SimpleDateFormat("yyyy-MM-dd");
											Calendar lCal = Calendar.getInstance();
											String lDate = lSdf.format(lCal.getTime());
											mQtDBHelper = new QuickTextDBHelper(QuickTextActivity.this);
											mQtDBHelper.updateQuickText(lId, lDetail, lDate,LoginActivity.g_username);
											mQtDBHelper.closeDB();
											queryQT();
											mSimpleAdapter = new MyAdapter(QuickTextActivity.this, mQktextList, R.layout.quicktextlist, from, to);
											mListView.setAdapter(mSimpleAdapter);
											mListView.invalidateViews();
										}
									}
								}).setNegativeButton("返回",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int whichButton) {
										dialog.cancel();
									}
								}).create().show();
			}else {
				singleChoose("请选择一项编辑!");
			}
			break;
		case 2:
			if (lCountChecked > 0) {
				new AlertDialog.Builder(this)
					.setTitle("删除提示")
					.setMessage("确认删除?")
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setPositiveButton("确认",
							new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									for (Integer pos : lPos) {
										String[] lStr = mSimpleAdapter.getView(pos, lView);
										mQtDBHelper = new QuickTextDBHelper(QuickTextActivity.this);
										mQtDBHelper.deleteQuickText(lStr[1]);
										mQtDBHelper.closeDB();
									}
									queryQT();
									mSimpleAdapter = new MyAdapter(QuickTextActivity.this, mQktextList, R.layout.quicktextlist, from, to);
									mListView.setAdapter(mSimpleAdapter);
									mListView.invalidateViews();
								}
							})
					.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								dialog.cancel();
							}
						}).create().show();
			} else {
				existChoose("请选择一项删除!");
			}
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void existChoose(String pMessage) {
		final AlertDialog.Builder lBuilder = new AlertDialog.Builder(
				QuickTextActivity.this);
		lBuilder.setTitle("提示");
		lBuilder.setMessage(pMessage);
		lBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		lBuilder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.cancel();
					}
				});
		lBuilder.create().show();
	}

	private void singleChoose(String pMessage) {
		final AlertDialog.Builder lBuilder = new AlertDialog.Builder(
				QuickTextActivity.this);
		lBuilder.setTitle("提示");
		lBuilder.setMessage(pMessage);
		lBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		lBuilder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						dialog.cancel();
					}
				});
		lBuilder.create().show();
	}

	public class MyAdapter extends SimpleAdapter {

		Map<Integer, Boolean> map;

		LayoutInflater mInflater;

		private List<? extends Map<String, ?>> mList;

		public MyAdapter(Context context, List<Map<String, String>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			map = new HashMap<Integer, Boolean>();
			mInflater = LayoutInflater.from(context);
			mList = data;
			for (int i = 0; i < data.size(); i++) {
				map.put(i, false);
			}
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(map.size() > 0) {
				convertView = mInflater.inflate(R.layout.quicktextlist, null);
				TextView tN = (TextView) convertView.findViewById(R.id.qklist_name);
				tN.setText(((String) mList.get(position).get("name")).split("::")[0]);
				CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.qklist_ck);
				checkBox.setChecked(map.get(position));
			}
			return convertView;
			
		}
		
		public String[] getView(int position, View convertView) {
			convertView = mInflater.inflate(R.layout.quicktextlist, null);
			String[] lStr = ((String) mList.get(position).get("name")).split("::");
			return new String[]{lStr[0], lStr[1]};
		}

	}

}
